package com.yjc.hire.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * </p>
 *
 * @author jcyin
 * @since 2025/9/7
 * </p>
 */

@Configuration
public class gatewayConfiguration {
    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public gatewayConfiguration(ServerCodecConfigurer serverCodecConfigurer, ObjectProvider<List<ViewResolver>>
                                viewResolversProvider) {
        this.serverCodecConfigurer = serverCodecConfigurer;
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
    }
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        return new SentinelGatewayBlockExceptionHandler(viewResolvers,serverCodecConfigurer);
    }

    @Bean
    @Order(-1)
    public GlobalFilter globalFilter() {
        return new SentinelGatewayFilter();
    }

    @PostConstruct
    public void doInit(){
        initGateWayRules();
    }

    private void initGateWayRules(){
        Set<GatewayFlowRule> rules = new HashSet<>();
        rules.add(new GatewayFlowRule("report-record-flow")
                .setCount(10)
                .setIntervalSec(1));
        GatewayRuleManager.loadRules(rules);
    }
}
